function [data, flag] = PARITY_CHECK(word,D29,D30)
% [data, flag] = PARITY_CHECK(data,D29,D30)
% 
% INPUTS
% data_in = the input data, one subframe (300 bits) at a time
% D29     = the D(29) parity bit from the PREVIOUS word
% D30     = the D(30) parity bit from the PREVIOUS word
% 
% OUTPUTS
% data    = the output data, corrected
% flag    = did parity pass?

%preinitialize the data output vector for speed
data = nan(1,300);
%set an error flag
flag = 1;
%step through the indices in steps of 30 = 1 word
%if bit D30 = 1, invert word
if(D30 == 1)
    word(1:24) = double(~word(1:24));
end
D = NaN(1,30);
%parity check the rest of the word
%note that modulo 2 addition is equivalent to xor
D(25) = mod(D29+word(1)+word(2)+word(3)+...
    word(5)+word(6)+word(10)+word(11)+...
    word(12)+word(13)+word(14)+word(17)+...
    word(18)+word(20)+word(23),2);
D(26) = mod(D30+word(2)+word(3)+word(4)+...
    word(6)+word(7)+word(11)+word(12)+...
    word(13)+word(14)+word(15)+word(18)+...
    word(19)+word(21)+word(24),2);
D(27) = mod(D29+word(1)+word(3)+word(4)+...
    word(5)+word(7)+word(8)+word(12)+...
    word(13)+word(14)+word(15)+word(16)+...
    word(19)+word(20)+word(22),2);
D(28) = mod(D30+word(2)+word(4)+word(5)+...
    word(6)+word(8)+word(9)+word(13)+...
    word(14)+word(15)+word(16)+word(17)+...
    word(20)+word(21)+word(23),2);
D(29) = mod(D30+word(1)+word(3)+word(5)+...
    word(6)+word(7)+word(9)+word(10)+...
    word(14)+word(15)+word(16)+word(17)+...
    word(18)+word(21)+word(22)+word(24),2);
D(30) = mod(D29+word(3)+word(5)+word(6)+...
    word(8)+word(9)+word(10)+word(11)+...
    word(13)+word(15)+word(19)+word(22)+...
    word(23)+word(24),2);
%does the parity check pass? compare the extracted D to the original
%word
if(double(D(25:30))==word(25:30))
    %the output data is word
    data = word;
else
    %it didn't pass, throw an error
    flag = 0;
    return;
end